import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Image } from './image.entity';
import { TableTemplateService } from '../../service/template.service';
import { TableTemplate } from '../../entities/template.entity';
import { existsSync, unlinkSync } from 'fs';
import { join } from 'path';

@Injectable()
export class ImagesService {
  constructor(
    @InjectRepository(Image)
    private imagesRepository: Repository<Image>,
    private templateService: TableTemplateService,
  ) {}

  async saveImage(
    file: Express.Multer.File,
    description?: string,
  ): Promise<Image> {
    const image = new Image();
    image.filename = file.filename;
    image.originalName = file.originalname;
    image.mimetype = file.mimetype;
    image.size = file.size;
    image.description = description;
    image.path = file.path;
    image.url = `/uploads/images/${file.filename}`;
    const savedImage = await this.imagesRepository.save(image);
    const template = new TableTemplate();
    template.pic_url = image.url;
    template.createTime = new Date();
    template.pic_description = "dddd";
    template.pic_name = "ceshi";
    template.type = 1;
    // 关联图片ID
    template.id = savedImage.id;
    await this.templateService.createTemplate(template);
    return savedImage;
  }

  async findAll(): Promise<Image[]> {
    return await this.imagesRepository.find({
      order: { createdAt: 'DESC' },
    });
  }

  async findOne(id: number): Promise<Image> {
    const image = await this.imagesRepository.findOne({ where: { id } });
    if (!image) {
      throw new BadRequestException('图片不存在');
    }
    return image;
  }

  async remove(id: number): Promise<void> {
    const image = await this.findOne(id);

    // 删除物理文件
    const filePath = join(process.cwd(), image.path);
    if (existsSync(filePath)) {
      unlinkSync(filePath);
    }

    await this.imagesRepository.delete(id);
  }
}
